<script setup lang="ts">
import { computed, h, onMounted, ref } from 'vue';
import type {
  DataTableColumns
} from 'naive-ui';
import {
  NAlert,
  NButton,
  NCard,
  NDataTable,
  NDatePicker,
  NDivider,
  NForm,
  NFormItem,
  NInput,
  NModal,
  NPopconfirm,
  NSelect,
  NSpace,
  useMessage,
} from "naive-ui";
import type { Value } from 'naive-ui/es/date-picker/src/interface';
import { $t } from "@/locales";
import {
  addSubtitle,
  deleteSubtitle,
  fetchLanguageOptions,
  fetchSubtitleList,
  updateSubtitle
} from "@/service/api";

const message = useMessage();

// 字幕列表
const subtitleList = ref<Api.Subtitle.SubtitleDto[]>([]);
// 加载状态
const loading = ref(false);
// 分页
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50],
});

// 搜索条件
const searchForm = ref({
  languageType: "",
  value: "",
  translatedLanguageType: "",
  translatedValue: "",
  // timeRange: null as [string, string] | null | undefined
  timeRange: null as Value | null | undefined
});

// 表单相关
const showModal = ref(false);
const modalTitle = ref("");
const formRef = ref<typeof NForm | null>(null);
const formValue = ref<Api.Subtitle.SubtitleVo>({
  languageType: "",
  value: "",
  translatedValue: "",
  translatedLanguageType: "",
});

// 表单验证规则
const rules = {
  languageType: {
    required: true,
    message: $t("page.subtitle.form.required.languageType"),
    trigger: ["blur", "change"],
  },
  value: {
    required: true,
    message: $t("page.subtitle.form.required.value"),
    trigger: ["blur", "input"],
  },
  translatedValue: {
    required: true,
    message: $t("page.subtitle.form.required.translatedValue"),
    trigger: ["blur", "input"],
  },
  translatedLanguageType: {
    required: true,
    message: $t("page.subtitle.form.required.translatedLanguageType"),
    trigger: ["blur", "change"],
  },
};
// 语言选项缓存
const languageOptions = ref<Api.Language.LanguageOption[]>([]);
let languageOptionsLoaded = false;

// 表格列定义
const columns = computed<DataTableColumns<Api.Subtitle.SubtitleDto>>(() => [
  {
    title: $t("page.subtitle.table.sourceLanguage"),
    key: "languageType",
    width: 100,
    fixed: "left",
    render: (row: Api.Subtitle.SubtitleDto) =>
      languageOptions.value.find((item) => item.value === row.languageType)
        ?.name || row.languageType,
  },
  {
    title: $t("page.subtitle.table.sourceText"),
    key: "value",
    width: 250,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: $t("page.subtitle.table.targetText"),
    key: "translatedValue",
    width: 250,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: $t("page.subtitle.table.targetLanguage"),
    key: "translatedLanguageType",
    width: 100,
    render: (row) =>
      languageOptions.value.find(
        (item) => item.value === row.translatedLanguageType
      )?.name || row.translatedLanguageType,
  },
  {
    title: $t("page.subtitle.table.triggerCount"),
    key: "triggerCount",
    width: 80,
    align: "center",
  },
  {
    title: $t("common.createTime"),
    key: "createTime",
    width: 150,
    align: "center",
  },
  {
    title: $t("common.updateTime"),
    key: "updateTime",
    width: 150,
    align: "center",
  },
  {
    title: $t("common.action"),
    key: "actions",
    width: 120,
    fixed: "right",
    align: "center",
    render: (row) =>
      h(NSpace, null, [
        h(
          NButton,
          {
            size: "small",
            type: "primary",
            secondary: true,
            onClick: () => handleEdit(row),
          },
          { default: () => $t("common.edit") }
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete(row.id),
          },
          {
            default: () => $t("common.confirmDelete"),
            trigger: () =>
              h(
                NButton,
                {
                  size: "small",
                  type: "error",
                  secondary: true,
                },
                { default: () => $t("common.delete") }
              ),
          }
        ),
      ]),
  },
]);



// 初始化数据
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function fetchData(page = pagination.value.page) {
  loading.value = true;
  try {
    if (!languageOptionsLoaded) {
      const options = await fetchLanguageOptions();
      languageOptions.value = options.data || [];
      languageOptionsLoaded = true;
    }
    // const list = await fetchSubtitleList({
    //   page,
    //   pageSize: pagination.value.pageSize,
    //   ...searchForm.value,
    // });
    // subtitleList.value = list.data || [];
    // pagination.value.itemCount = list.total || 0;
  } catch {
    message.error($t("page.subtitle.message.loadFailed"));
  } finally {
    loading.value = false;
  }
}

// 处理分页变化
function handlePageChange(page: number) {
  pagination.value.page = page;
  fetchData(page);
}

// 处理每页条数变化
function handlePageSizeChange(pageSize: number) {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  fetchData(1);
}

// 优化搜索防抖
const searchDebounce = ref<number>();
function handleSearch() {
  if (searchDebounce.value) {
    clearTimeout(searchDebounce.value);
  }
  searchDebounce.value = window.setTimeout(() => {
    pagination.value.page = 1;
    fetchData(1);
  }, 300);
}

// 重置搜索
function handleReset() {
  searchForm.value = {
    languageType: "",
    value: "",
    translatedLanguageType: "",
    translatedValue: "",
    timeRange: null,
  };
  handleSearch();
}

// 添加字幕
function handleAdd() {
  modalTitle.value = $t("page.subtitle.modal.add");
  formValue.value = {
    languageType: "",
    value: "",
    translatedValue: "",
    translatedLanguageType: "",
  };
  showModal.value = true;
}

// 编辑字幕
function handleEdit(row: Api.Subtitle.SubtitleDto) {
  modalTitle.value = $t("page.subtitle.modal.edit");
  formValue.value = {
    id: row.id,
    languageType: row.languageType,
    value: row.value,
    translatedValue: row.translatedValue,
    translatedLanguageType: row.translatedLanguageType,
    triggerCount: row.triggerCount,
    source: row.source,
    sourcePath: row.sourcePath,
  };
  showModal.value = true;
}

// 删除字幕
async function handleDelete(id: string) {
  try {
    await deleteSubtitle(id);
    message.success($t("page.subtitle.message.deleteSuccess"));
    if (subtitleList.value.length === 1 && pagination.value.page > 1) {
      // pagination.value.page --;
      pagination.value.page -= 1;
    }
    await fetchData(pagination.value.page);
  } catch {
    message.error($t("page.subtitle.message.deleteFailed"));
  }
}

// 优化表单验证
const validateForm = () => {
  return new Promise((resolve, reject) => {
    formRef.value?.validate((errors: any) => {
      if (!errors) {
        resolve(true);
      } else {
        reject(errors);
      }
    });
  });
};

// 优化表单提交
async function handleSubmit() {
  try {
    await validateForm();
    const api = formValue.value.id ? updateSubtitle : addSubtitle;
    await api(formValue.value);
    message.success($t("page.subtitle.message.saveSuccess"));
    showModal.value = false;
    await fetchData(pagination.value.page);
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message);
    } else {
      message.error($t("page.subtitle.message.saveFailed"));
    }
  }
}

// 过滤语言选项的函数
function filterLanguageOptions(
  inputValue: string,
  options: Api.Language.LanguageOption[]
) {
  if (!inputValue) return options;
  const searchValue = inputValue.toLowerCase();
  return options.filter(
    (option) =>
      option.name.toLowerCase().includes(searchValue) ||
      option.value.toLowerCase().includes(searchValue)
  );
}

// 搜索状态
const searchValue = ref("");
const debouncedSearch = computed(() => {
  const value = searchValue.value.toLowerCase();
  return languageOptions.value.filter(
    (option) =>
      option.name.toLowerCase().includes(value) ||
      option.value.toLowerCase().includes(value)
  );
});

const filteredOptions = computed<Api.Language.LanguageOption[]>(() => {
  if (!searchValue.value) return languageOptions.value;
  return debouncedSearch.value;
});

onMounted(fetchData);
</script>

<template>
  <div class="p-4">
    <NCard :bordered="false">
      <NSpace vertical :size="16">
        <!-- 页面说明 -->
        <NAlert
          type="info"
          :title="$t('page.subtitle.tips.title')"
          class="mb-4"
        >
          {{ $t("page.subtitle.tips.content") }}
        </NAlert>

        <!-- 搜索区域 -->
        <NCard :bordered="false" size="small">
          <NSpace vertical :size="12">
            <NSpace :size="16" wrap>
              <NSpace :size="12" vertical>
                <span class="text-sm text-gray-500">{{
                  $t("page.subtitle.form.language")
                }}</span>
                <NSpace :size="12">
                  <NSelect
                    v-model:value="searchForm.languageType"
                    filterable
                    :show-arrow="true"
                    :on-search="
                                        (value:string) => {
                                          searchValue = value;
                                        }
                                      "
                    :options="
                                        filteredOptions.map((item) => ({
                                          label: item.name,
                                          value: item.value,
                                        }))
                                      "
                    :placeholder="$t('page.subtitle.form.sourceLanguage')"
                    clearable
                    style="width: 180px"
                  />
                  <NSelect
                    v-model:value="searchForm.translatedLanguageType"
                    filterable
                    :show-arrow="true"
                    :on-search="
                                        (value:string) => {
                                          searchValue = value;
                                        }
                                      "
                    :options="
                                        filteredOptions.map((item) => ({
                                          label: item.name,
                                          value: item.value,
                                        }))
                                      "
                    :placeholder="$t('page.subtitle.form.targetLanguage')"
                    clearable
                    style="width: 180px"
                  />
                </NSpace>
              </NSpace>
              <NDivider style="margin: 12px 0" />
              <NSpace :size="12" vertical>
                <span class="text-sm text-gray-500">{{
                  $t("page.subtitle.form.content")
                }}</span>
                <NSpace :size="12">
                  <NInput
                    v-model:value="searchForm.value"
                    :placeholder="$t('page.subtitle.form.sourceText')"
                    clearable
                    style="width: 180px"
                  />
                  <NInput
                    v-model:value="searchForm.translatedValue"
                    :placeholder="$t('page.subtitle.form.targetText')"
                    clearable
                    style="width: 180px"
                  />
                </NSpace>
              </NSpace>
              <NSpace :size="12" vertical>
                <span class="text-sm text-gray-500">{{
                  $t("page.subtitle.form.time")
                }}</span>
                <NDatePicker
                  v-model:value="searchForm.timeRange"
                  type="datetimerange"
                  clearable
                  :placeholder="[$t('common.startTime'), $t('common.endTime')].join(', ')"
                  style="width: 380px"
                />
              </NSpace>
            </NSpace>
            <NSpace :size="12" justify="end">
              <NButton @click="handleReset">
                {{ $t("common.reset") }}
              </NButton>
              <NButton type="primary" @click="handleSearch">
                {{ $t("common.search") }}
              </NButton>
            </NSpace>
          </NSpace>
        </NCard>

        <!-- 操作按钮区 -->
        <NSpace justify="end">
          <NButton type="primary" @click="handleAdd">
            {{ $t("common.add") }}
          </NButton>
        </NSpace>

        <!-- 字幕列表 -->
        <NDataTable
          :loading="loading"
          :columns="columns"
          :data="subtitleList"
          :bordered="false"
          :single-line="false"
          striped
          :pagination="pagination"
          :scroll-x="1200"
          style="margin-top: 8px"
          virtual-scroll
          :row-key="(row:Api.Subtitle.SubtitleDto) => row.id"
          :max-height="400"
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </NSpace>
    </NCard>

    <!-- 编辑弹窗 -->
    <NModal
      v-model:show="showModal"
      :title="modalTitle"
      preset="dialog"
      :show-icon="false"
    >
      <NForm
        ref="formRef"
        :model="formValue"
        :rules="rules"
        label-placement="left"
        label-width="120"
        require-mark-placement="right-hanging"
      >
        <NFormItem
          :label="$t('page.subtitle.form.sourceLanguage')"
          path="languageType"
        >
          <NSelect
            v-model:value="formValue.languageType"
            filterable
            :show-arrow="true"
            :on-search="
              (value:string) => {
                searchValue = value;
              }
            "
            :options="
              filteredOptions.map((item:Api.Language.LanguageOption) => ({
                label: item.name,
                value: item.value,
              }))
            "
          />
        </NFormItem>

        <NFormItem :label="$t('page.subtitle.form.sourceText')" path="value">
          <NInput v-model:value="formValue.value" type="textarea" :rows="3" />
        </NFormItem>

        <NFormItem
          :label="$t('page.subtitle.form.targetText')"
          path="translatedValue"
        >
          <NInput
            v-model:value="formValue.translatedValue"
            type="textarea"
            :rows="3"
          />
        </NFormItem>

        <NFormItem
          :label="$t('page.subtitle.form.targetLanguage')"
          path="translatedLanguageType"
        >
          <NSelect
            v-model:value="formValue.translatedLanguageType"
            filterable
            :show-arrow="true"
            :on-search="
              (value:string) => {
                searchValue = value;
              }
            "
            :options="
              filteredOptions.map((item:Api.Language.LanguageOption) => ({
                label: item.name,
                value: item.value,
              }))
            "
          />
        </NFormItem>
      </NForm>

      <template #action>
        <NSpace justify="end">
          <NButton @click="showModal = false">
            {{ $t("common.cancel") }}
          </NButton>
          <NButton type="primary" @click="handleSubmit">
            {{ $t("common.confirm") }}
          </NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>
